'''
Created on Aug 17, 2010

@author: riche
'''

import subprocess, shlex

class Copier(object):
    '''
    classdocs
    '''


    def __init__(self, s_hst='', s_file='', d_hst='', d_file=''):
        '''
        Constructor
        '''
        self._src_host = s_hst
        self._src_file = s_file
        self._dest_host = d_hst
        self._dest_file = d_file
        
    def get_src_string(self):
        '''Returns the correctly formatted scp source string'''
        return self.format_name(self._src_host, self._src_file)
        
    def get_dest_string(self):
        '''Returns the correctly formatted scp destination string'''
        return self.format_name(self._dest_host, self._dest_file)
    
    def format_name(self, host, file):
        if file is None or file == '':
            raise BadCopyArgumentException('{}:{} is not valid'.format(host, file))
        if host is None or host == '':
            return file
        else:
            return '{}:{}'.format(host, file)
        
    
    def copy(self):
        command_string = 'scp {} {}'.format(self.get_src_string(), self.get_dest_string())
        commands = shlex.split(command_string)
        p = subprocess.Popen(commands, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
        status = p.wait()
        if status != 0:
            raise CopyFailedException
        
class CopyFailedException(Exception):
    '''Raised when a copy is not successful'''
    
class BadCopyArgumentException(Exception):
    '''Raised when an empty file name is given'''